/**
 * 语言处理工具函数
 */

import { LanguageFile, LanguageData, ConflictResult, DetectionReport, GeneratedFile } from '../types';

/**
 * 生成Dart语言文件内容
 */
export const generateDartFileContent = (languageFile: LanguageFile): string => {
  const { code, data } = languageFile;
  
  // 生成Dart文件内容
  let content = `const Map<String, String> ${code} = {\n`;
  
  // 按字母顺序排序键
  const sortedKeys = Object.keys(data).sort();
  
  sortedKeys.forEach((key, index) => {
    const value = data[key];
    const escapedValue = escapeDartString(value);
    const isLast = index === sortedKeys.length - 1;
    content += `  "${key}": "${escapedValue}"${isLast ? '' : ','}\n`;
  });
  
  content += '};';
  
  return content;
};

/**
 * 生成Dart语言文件内容（新格式，兼容docs/langs目录）
 */
export const generateDartFileContentForDocs = (languageFile: LanguageFile): string => {
  const { code, data } = languageFile;
  
  // 生成Dart文件内容，使用docs/langs目录的格式
  let content = `// ${languageFile.language} language file\n`;
  content += `// Generated automatically - do not edit manually\n\n`;
  content += `const Map<String, String> ${code} = {\n`;
  
  // 按字母顺序排序键
  const sortedKeys = Object.keys(data).sort();
  
  sortedKeys.forEach((key, index) => {
    const value = data[key];
    const escapedValue = escapeDartString(value);
    const isLast = index === sortedKeys.length - 1;
    content += `  "${key}": "${escapedValue}"${isLast ? '' : ','}\n`;
  });
  
  content += '};\n';
  
  return content;
};

/**
 * 转义Dart字符串
 */
const escapeDartString = (str: string): string => {
  return str
    .replace(/\\/g, '\\\\')
    .replace(/"/g, '\\"')
    .replace(/\n/g, '\\n')
    .replace(/\r/g, '\\r')
    .replace(/\t/g, '\\t');
};

/**
 * 检测翻译冲突
 */
export const detectConflicts = (languageFiles: LanguageFile[]): DetectionReport => {
  const conflicts: ConflictResult[] = [];
  const allKeys = new Set<string>();
  const languageKeys: { [language: string]: Set<string> } = {};
  
  // 收集所有键和语言
  languageFiles.forEach(file => {
    languageKeys[file.code] = new Set(Object.keys(file.data));
    Object.keys(file.data).forEach(key => allKeys.add(key));
  });
  
  // 检测缺失的翻译
  allKeys.forEach(key => {
    const missingLanguages: string[] = [];
    
    languageFiles.forEach(file => {
      if (!file.data[key] || file.data[key].trim() === '') {
        missingLanguages.push(file.code);
      }
    });
    
    if (missingLanguages.length > 0) {
      conflicts.push({
        type: 'missing',
        key,
        languages: missingLanguages,
        message: `键 "${key}" 在以下语言中缺失翻译: ${missingLanguages.join(', ')}`,
        severity: missingLanguages.length === languageFiles.length ? 'high' : 'medium',
      });
    }
  });
  
  // 检测重复的键
  const keyCounts: { [key: string]: number } = {};
  languageFiles.forEach(file => {
    Object.keys(file.data).forEach(key => {
      keyCounts[key] = (keyCounts[key] || 0) + 1;
    });
  });
  
  Object.entries(keyCounts).forEach(([key, count]) => {
    if (count > languageFiles.length) {
      conflicts.push({
        type: 'duplicate',
        key,
        languages: [],
        message: `键 "${key}" 出现重复`,
        severity: 'high',
      });
    }
  });
  
  // 检测格式错误
  languageFiles.forEach(file => {
    Object.entries(file.data).forEach(([key, value]) => {
      if (value && typeof value === 'string') {
        // 检测可能的格式问题
        if (value.includes('\\n') && !value.includes('\\n')) {
          conflicts.push({
            type: 'format_error',
            key,
            languages: [file.code],
            message: `键 "${key}" 在语言 ${file.code} 中可能存在换行符格式问题`,
            severity: 'low',
          });
        }
      }
    });
  });
  
  // 生成报告
  const report: DetectionReport = {
    totalKeys: allKeys.size,
    totalLanguages: languageFiles.length,
    conflicts,
    summary: {
      duplicates: conflicts.filter(c => c.type === 'duplicate').length,
      missing: conflicts.filter(c => c.type === 'missing').length,
      formatErrors: conflicts.filter(c => c.type === 'format_error').length,
    },
  };
  
  return report;
};

/**
 * 生成语言文件
 */
export const generateLanguageFiles = (languageFiles: LanguageFile[]): GeneratedFile[] => {
  return languageFiles.map(file => {
    const content = generateDartFileContent(file);
    return {
      language: file.language,
      code: file.code,
      fileName: file.fileName,
      content,
      size: new Blob([content]).size,
    };
  });
};

/**
 * 验证语言文件数据
 */
export const validateLanguageData = (data: LanguageData): { isValid: boolean; errors: string[] } => {
  const errors: string[] = [];
  
  Object.entries(data).forEach(([key, value]) => {
    if (!key || key.trim() === '') {
      errors.push('发现空的键名');
    }
    
    if (typeof value !== 'string') {
      errors.push(`键 "${key}" 的值不是字符串类型`);
    }
  });
  
  return {
    isValid: errors.length === 0,
    errors,
  };
};

/**
 * 获取语言文件统计信息
 */
export const getLanguageFileStats = (languageFiles: LanguageFile[]) => {
  const totalKeys = new Set<string>();
  let totalTranslations = 0;
  let emptyTranslations = 0;
  
  languageFiles.forEach(file => {
    Object.keys(file.data).forEach(key => totalKeys.add(key));
    Object.values(file.data).forEach(value => {
      if (value && value.trim() !== '') {
        totalTranslations++;
      } else {
        emptyTranslations++;
      }
    });
  });
  
  return {
    totalLanguages: languageFiles.length,
    totalKeys: totalKeys.size,
    totalTranslations,
    emptyTranslations,
    completionRate: totalKeys.size > 0 ? (totalTranslations / (totalKeys.size * languageFiles.length)) * 100 : 0,
  };
};
